<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchProjectList, deleteProject, archiveProject, restoreProject } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import ProjectOperateDrawer from './modules/project-operate-drawer.vue';
import ProjectMemberDrawer from './modules/project-member-drawer.vue';
import ProjectStatisticsModal from './modules/project-statistics-modal.vue';

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();
const { bool: operateDrawerVisible, setTrue: openOperateDrawer, setFalse: closeOperateDrawer } = useBoolean();
const { bool: memberDrawerVisible, setTrue: openMemberDrawer, setFalse: closeMemberDrawer } = useBoolean();
const { bool: statisticsModalVisible, setTrue: openStatisticsModal, setFalse: closeStatisticsModal } = useBoolean();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  code: '',
  status: undefined as number | undefined
});

const tableData = ref<Api.Dataplatform.Project[]>([]);
const total = ref(0);
const operateType = ref<'add' | 'edit'>('add');
const editingId = ref<number>();
const selectedProjectId = ref<number>();

const columns = [
  { key: 'code', title: '项目编码', width: 150 },
  { key: 'name', title: '项目名称', width: 200 },
  { key: 'ownerName', title: '负责人', width: 120 },
  {
    key: 'status',
    title: '状态',
    width: 100,
    render: (row: Api.Dataplatform.Project) => {
      if (row.status === 1) {
        return h(NTag, { type: 'success' }, { default: () => '正常' });
      }
      return h(NTag, { type: 'warning' }, { default: () => '归档' });
    }
  },
  { key: 'memberCount', title: '成员数', width: 100 },
  { key: 'datasourceCount', title: '数据源', width: 100 },
  { key: 'modelCount', title: '数据模型', width: 100 },
  { key: 'etlTaskCount', title: 'ETL任务', width: 100 },
  { key: 'startDate', title: '开始日期', width: 120 },
  { key: 'endDate', title: '结束日期', width: 120 },
  { key: 'createTime', title: '创建时间', width: 180 },
  {
    key: 'actions',
    title: '操作',
    width: 300,
    fixed: 'right' as const,
    render: (row: Api.Dataplatform.Project) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, { size: 'small', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
          h(NButton, { size: 'small', onClick: () => handleViewMembers(row.id!) }, { default: () => '成员管理' }),
          h(NButton, { size: 'small', onClick: () => handleViewStatistics(row.id!) }, { default: () => '资源统计' }),
          row.status === 1 
            ? h(NPopconfirm, { onPositiveClick: () => handleArchive(row.id!) }, {
                default: () => '确定归档该项目吗？',
                trigger: () => h(NButton, { size: 'small', type: 'warning' }, { default: () => '归档' })
              })
            : h(NButton, { size: 'small', type: 'info', onClick: () => handleRestore(row.id!) }, { default: () => '恢复' }),
          h(NPopconfirm, { onPositiveClick: () => handleDelete(row.id!) }, {
            default: () => '确定删除该项目吗？删除后不可恢复！',
            trigger: () => h(NButton, { size: 'small', type: 'error' }, { default: () => '删除' })
          })
        ]
      });
    }
  }
];

async function getTableData() {
  startLoading();
  const { data, error } = await fetchProjectList(queryParams);
  if (!error) {
    tableData.value = data?.rows || [];
    total.value = data?.total || 0;
  }
  endLoading();
}

function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    code: '',
    status: undefined
  });
  getTableData();
}

function handleAdd() {
  operateType.value = 'add';
  editingId.value = undefined;
  openOperateDrawer();
}

function handleEdit(row: Api.Dataplatform.Project) {
  operateType.value = 'edit';
  editingId.value = row.id;
  openOperateDrawer();
}

async function handleDelete(id: number) {
  const { error } = await deleteProject(id);
  if (!error) {
    window.$message?.success('删除成功');
    getTableData();
  }
}

async function handleArchive(id: number) {
  const { error } = await archiveProject(id);
  if (!error) {
    window.$message?.success('归档成功');
    getTableData();
  }
}

async function handleRestore(id: number) {
  const { error } = await restoreProject(id);
  if (!error) {
    window.$message?.success('恢复成功');
    getTableData();
  }
}

function handleViewMembers(id: number) {
  selectedProjectId.value = id;
  openMemberDrawer();
}

function handleViewStatistics(id: number) {
  selectedProjectId.value = id;
  openStatisticsModal();
}

function handleOperateSuccess() {
  closeOperateDrawer();
  getTableData();
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

// 初始化
getTableData();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="项目管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新建项目
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NInput v-model:value="queryParams.name" placeholder="项目名称" clearable class="w-200px" />
            <NInput v-model:value="queryParams.code" placeholder="项目编码" clearable class="w-200px" />
            <NSelect
              v-model:value="queryParams.status"
              placeholder="状态"
              clearable
              class="w-150px"
              :options="[
                { label: '正常', value: 1 },
                { label: '归档', value: 0 }
              ]"
            />
          </NSpace>
          <NSpace>
            <NButton type="primary" @click="handleQuery">
              <icon-ic-round-search class="mr-4px text-20px" />
              查询
            </NButton>
            <NButton @click="handleReset">
              <icon-ic-round-refresh class="mr-4px text-20px" />
              重置
            </NButton>
          </NSpace>
        </NSpace>

        <NDataTable
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :scroll-x="1800"
          :pagination="{
            page: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            itemCount: total,
            showSizePicker: true,
            pageSizes: [10, 20, 50, 100],
            onUpdatePage: handlePageChange,
            onUpdatePageSize: handlePageSizeChange
          }"
          class="flex-1-hidden"
        />
      </div>
    </NCard>

    <ProjectOperateDrawer
      v-model:visible="operateDrawerVisible"
      :operate-type="operateType"
      :row-id="editingId"
      @success="handleOperateSuccess"
    />

    <ProjectMemberDrawer
      v-model:visible="memberDrawerVisible"
      :project-id="selectedProjectId"
    />

    <ProjectStatisticsModal
      v-model:visible="statisticsModalVisible"
      :project-id="selectedProjectId"
    />
  </div>
</template>
